#include "MakeManager.h"
#include "chainsaw.h"

MakeManager::MakeManager(std::string gen_path) : gen_path_(gen_path), writer_(gen_path + "/main.cc", std::ios::out)
{
}

void MakeManager::init()
{
    write("#include <iostream>");
    write("#include <fstream>");
    write("#include <string>");
    write("using namespace std;");
}

std::string get_invalid_name(std::string name)
{
    std::string res;
    for(auto c : name)
    {
        if (chainsaw::is_alnum(c) || c == '_')
        {
            res+= c;
        }
        else
        {
            res+='_';
        }
    }
    return res;
}

void MakeManager::write_method(std::string const &file_name, std::string const &file_extension, std::vector<std::string> const &data)
{
    method_list_.push_back({file_name, file_extension});
    auto invalid_name = get_invalid_name(file_name);
    auto invalid_ext = get_invalid_name(file_extension);
    method_list_invalid_name_.push_back({invalid_name,invalid_ext});

    write("void write_", invalid_name, invalid_ext, "()");
    write("{");
    // todo
    // substr is too long
    write("    fstream file(\"", file_name, ".", cns::stringtool(file_extension).substr(1, static_cast<int>(file_extension.size())), "\", std::ios::out);");
    for (auto t : data)
        write("    file << \"", t, "\" << endl;");
    write("}");
}

void MakeManager::write_main()
{
    write("int main()");
    write("{");
    for (auto t : method_list_invalid_name_)
    {
        write("    write_", t.name, t.ext, "();");
    }
    write("   return 0;");
    write("}");
}

void MakeManager::write_CMakeLists_txt()
{
    std::fstream w(gen_path_ + "/CMakeLists.txt", std::ios::out);

    w << "cmake_minimum_required(VERSION 3.15)" << std::endl;
    w << "project(hi)" << std::endl;
    w << "add_executable(make main.cc)" << std::endl;
    w.close();
}

MakeManager::~MakeManager()
{
    writer_.close();
}

bool MakeManager::is_writer_ok() const
{
    return writer_.is_open();
}
